//
//  GKZYLoginViewController.m
//  GKZY_CLASS
//
//  Created by KwokChun Cheung on 15/11/30.
//  Copyright © 2015年 eenet. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Masonry/Masonry.h>
#import <JGProgressHUD/JGProgressHUD.h>

#import "GKZY_CLASS.h"
#import "GKZYLoginReq.h"
#import "GKZYLoginViewController.h"
#import "GKZYHomeViewController.h"
#import "GKZYHomeTabBarViewController.h"
#import "GKZYLoginUserInfoEntity.h"

#import "ApiGuoKaiHepler.h"
#import "ClassHelper.h"
#import "Base64Helper.h"
#import "xxptmobile-Defines.h"



@interface GKZYLoginViewController()<UITextFieldDelegate>
@property (nonatomic, strong) UIScrollView *mainScroll;
@property (nonatomic, strong) UIView *mainScrollArea;

@property (nonatomic, strong) UIImageView *logoImage;
@property (nonatomic, strong) UIView *sloganArea;
@property (nonatomic, strong) UILabel *sloganLabel;
@property (nonatomic, strong) UITextField *accountField;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UIButton *logButton;

@property (nonatomic, strong) GKZYLoginModel *model;
@end

@implementation GKZYLoginViewController{
    BOOL isLogout;
    
    CGFloat sizeForWord;
    UIColor *colorForWord;
    CGFloat sizeForFieldIcon;
    
    UITextField *editingField;
    
    JGProgressHUD *progress;
    ApiGuoKaiHepler *apiHepler;
}

//-(UIStatusBarStyle)preferredStatusBarStyle{
//    return UIStatusBarStyleLightContent;
//}

-(instancetype)init{
    if (self = [super init]) {
        sizeForWord = 18;
        colorForWord = [UIColor grayColor];
        sizeForFieldIcon = 24;
        
        progress = [[JGProgressHUD alloc]initWithStyle:JGProgressHUDStyleDark];
        apiHepler = [ApiGuoKaiHepler new];
        
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        
        self.view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.mainScroll];
        [self.mainScroll mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(self.view);
        }];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alterError:) name:OO_LOGIN_USER_ERROR object:nil];
        
    }
    return self;
}

-(instancetype)initOnLogout{
    if (self = [self init]) {
        isLogout = YES;
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults removeObjectForKey:OO_USER_INFO_KEY];
        [userDefaults removeObjectForKey:KEY_HOME_TABLE_CACHE];
        [userDefaults removeObjectForKey:KEY_CURRENT_STUDENTINFO];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeContentViewPosition:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeContentViewPosition:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

#pragma mark - Request Methods //请求方法只负责注销loading

-(void)requestLoginBy:(NSString *)account andPassword:(NSString *)password{
    
    NSString *testFlag = @"###";
    NSRange testFlagRange = [account rangeOfString:testFlag];
//    头三个字符为井号,账号登录时才能转换
    if (testFlagRange.length==testFlag.length && testFlagRange.location == 0) {
        [apiHepler setIsTest:[apiHepler archiveIsTest]];
        account = [account substringFromIndex:testFlagRange.length];
    }else{
        [apiHepler setIsTest:NO];
    }
    
//    /*******************测试数据******************/
//    [apiHepler setIsTest:YES];
//    /*******************测试数据******************/
    
    GKZYLoginReq *req = [GKZYLoginReq new];
    req.LoginName = account;
    req.Password = [Base64Helper base64StringFromText:password];
    req.rule = @"standard";
    req.eeIM = @"N";
    
    [apiHepler toPOST:API_KEY_LOGIN andReq:req andContentType:GKZYJsonContentType andSync:YES andSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *errorMsg = responseObject[@"resultMsg"];
        if (!errorMsg) {
            errorMsg = responseObject[@"RESULT_MSG"];
        }
        if (errorMsg) {
            [self alterErrorWithMsg:errorMsg];
            [progress dismissAfterDelay:0.1f];
            return;
        }
        
        GKZYLoginUserInfoEntity *entity = [GKZYLoginUserInfoEntity new];
        [ClassHelper copyDicFrom:responseObject to:entity];
        NSData *entityData = [NSKeyedArchiver archivedDataWithRootObject:entity];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:entityData forKey:OO_USER_INFO_KEY];
        
        [progress dismissAfterDelay:0.1f];
        
        GKZYHomeTabBarViewController *vc = [[GKZYHomeTabBarViewController alloc]initWithSid:entity.sid];
        [self presentViewController:vc animated:NO completion:nil];
        
    } andFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self alterErrorWithMsg:@"登录有误, 请重新登录."];
        [progress dismissAfterDelay:0.1f];
    }];
}



#pragma mark - Respones Methods

-(void)loginForButton:(UIButton *)button{
    [progress showInView:self.view animated:YES];
    
    [self hideKeyBoard];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self requestLoginBy:self.accountField.text andPassword:self.passwordField.text];
    });
}

-(void)alterMsg:(NSString *)resultMsg{
    if (resultMsg && [resultMsg isEqualToString:@"LOGIN_NAME IS NULL"]) {
        [self alert:@"账号为空" withComplete:nil];
    }else if (resultMsg && [resultMsg isEqualToString:@"Password IS NULL"]){
        [self alert:@"密码为空" withComplete:nil];
    }else if (resultMsg && [resultMsg isEqualToString:@"SYSTEM_ERROR"]){
        [self alert:@"用户名或密码错误" withComplete:nil];
    }
}

-(void)changeContentViewPosition:(NSNotification *)not{
    NSDictionary *userInfo = [not userInfo];
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    CGFloat keyboardY = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    
    CGFloat editingFieldOffset = editingField.frame.origin.y + editingField.frame.size.height;
    CGFloat scrollAdjustOffset = editingFieldOffset - keyboardY;
    
    //键盘未遮盖不触发
    if (not.name == UIKeyboardWillShowNotification &&
        keyboardY > editingFieldOffset ) {
        return;
    }
    
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
        
        CGPoint scrollOffset = self.mainScroll.contentOffset;
        if (not.name == UIKeyboardWillShowNotification) {
            //编辑Y轴+编辑高度 - 键盘最终的Y轴 = 调整差
            scrollOffset.y = scrollAdjustOffset;
        }else if (not.name == UIKeyboardWillHideNotification){
            scrollOffset.y = 0;
        }
        
        self.mainScroll.contentOffset = scrollOffset;
        
    }];
}

#pragma mark - UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    editingField = textField;//获取正在编辑的textField
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    editingField = nil;
}

#pragma mark - Setter For Property

-(void)setModel:(GKZYLoginModel *)model{
    _model = model;
}

#pragma mark - Getter For UI

-(UIScrollView *)mainScroll{
    if (!_mainScroll) {
        _mainScroll = ({
            UIScrollView *scroll = [UIScrollView new];
            [scroll addSubview:self.mainScrollArea];
            [self.mainScrollArea mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.bottom.equalTo(scroll);
                make.height.width.equalTo(scroll);
            }];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyBoard)];
            [scroll addGestureRecognizer:tap];
            
            scroll;
        });
    }
    return _mainScroll;
}

-(UIView *)mainScrollArea{
    if (!_mainScrollArea) {
        _mainScrollArea = ({
            UIView *view = [UIView new];
            [view addSubview:self.logoImage];
            [self.logoImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(view).offset(100);
                make.centerX.equalTo(view);
                make.height.equalTo(view.mas_height).multipliedBy(0.18);
                make.width.equalTo(view.mas_width).multipliedBy(0.7);
            }];
            
            [view addSubview:self.sloganArea];
            [self.sloganArea mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.logoImage.mas_bottom).offset(30);
                make.left.right.equalTo(view);
            }];
            
            [view addSubview:self.accountField];
            [self.accountField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.sloganArea.mas_bottom).offset(30);
                make.left.equalTo(view).offset(-1);
                make.right.equalTo(view).offset(1);
                make.height.equalTo(@(50));
            }];
            
            [view addSubview:self.passwordField];
            [self.passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.accountField.mas_bottom).offset(-1);
                make.left.equalTo(view).offset(-1);
                make.right.equalTo(view).offset(1);
                make.height.equalTo(@(50));
            }];
            
            [view addSubview:self.logButton];
            [self.logButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.passwordField.mas_bottom).offset(30);
                make.left.equalTo(view).offset(10);
                make.right.equalTo(view).offset(-10);
                make.height.equalTo(@(50));
            }];
            view;
        });
    }
    return _mainScrollArea;
}

-(UIImageView*)logoImage{
    if (!_logoImage) {
        _logoImage = ({
            UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"logo1"]];
            imageView;
        });
    }
    return _logoImage;
}

-(UIView *)sloganArea{
    if (!_sloganArea) {
        _sloganArea = ({
            UIView *view = [UIView new];
            
            UILabel *lineLeft = [UILabel new];
            lineLeft.backgroundColor = [UIColor lightGrayColor];
            [view addSubview:lineLeft];
            [lineLeft mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(view);
                make.height.equalTo(@(0.8));
                make.left.equalTo(view).offset(10);
            }];
            
            UILabel *lineRight = [UILabel new];
            lineRight.backgroundColor = [UIColor lightGrayColor];
            [view addSubview:lineRight];
            [lineRight mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(view);
                make.height.equalTo(@(0.8));
                make.right.equalTo(view).offset(-10);
            }];
            
            UILabel *sloganLabel = [UILabel new];
            sloganLabel.textColor = [UIColor lightGrayColor];
            sloganLabel.text = @"点滴时间碎片 浩瀚学习空间";
            sloganLabel.font = [UIFont systemFontOfSize:sizeForWord];
            [sloganLabel sizeToFit];
            [view addSubview:sloganLabel];
            [sloganLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(view);
                make.left.equalTo(lineLeft.mas_right).offset(8);
                make.right.equalTo(lineRight.mas_left).offset(-8);
                make.centerX.equalTo(view);
                make.width.equalTo(@(100)).priorityHigh();
            }];
            self.sloganLabel = sloganLabel;
            
            view;
        });
    }
    return _sloganArea;
}

-(UITextField *)accountField{
    if (!_accountField) {
        _accountField = ({
            UITextField *field = [UITextField new];
            field.delegate = self;
            
            CGFloat gapForIcon = 10;
            UIFont *fontForIcon = [UIFont fontWithName:OO_FONT_NAME size:sizeForFieldIcon];
            UIImageView *icon = [[UIImageView alloc]initWithImage:[self imageWithText:@"K" font:fontForIcon iconColor:[UIColor lightGrayColor] imageSize:CGSizeMake(sizeForFieldIcon, sizeForFieldIcon)]];
            UIView *iconArea = [[UIView alloc]initWithFrame:CGRectMake(0, 0, sizeForFieldIcon + (gapForIcon*2), sizeForFieldIcon)];
            [iconArea addSubview:icon];
            [icon mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(iconArea);
                make.left.equalTo(iconArea).offset(gapForIcon);
                make.right.equalTo(iconArea).offset(-gapForIcon);
            }];
            
            field.leftView = iconArea;
            field.leftViewMode = UITextFieldViewModeAlways;
            field.placeholder = @"请输入账号";
            field.font = [UIFont systemFontOfSize:sizeForWord];
            field.textColor = colorForWord;
            field.layer.borderWidth = 1;
            field.layer.borderColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1].CGColor;
            field;
        });
    }
    return _accountField;
}

-(UITextField *)passwordField{
    if (!_passwordField) {
        _passwordField = ({
            UITextField *field = [UITextField new];
            field.secureTextEntry = YES;
            field.delegate = self;
            
            CGFloat gapForIcon = 10;
            UIFont *fontForIcon = [UIFont fontWithName:OO_FONT_NAME size:sizeForFieldIcon];
            UIImageView *icon = [[UIImageView alloc]initWithImage:[self imageWithText:@"L" font:fontForIcon iconColor:[UIColor lightGrayColor] imageSize:CGSizeMake(sizeForFieldIcon, sizeForFieldIcon)]];
            UIView *iconArea = [[UIView alloc]initWithFrame:CGRectMake(0, 0, sizeForFieldIcon + (gapForIcon*2), sizeForFieldIcon)];
            [iconArea addSubview:icon];
            [icon mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(iconArea);
                make.left.equalTo(iconArea).offset(gapForIcon);
                make.right.equalTo(iconArea).offset(-gapForIcon);
            }];
            
            field.leftView = iconArea;
            field.leftViewMode = UITextFieldViewModeAlways;
            field.placeholder = @"请输入密码";
            field.font = [UIFont systemFontOfSize:sizeForWord];
            field.textColor = colorForWord;
            field.layer.borderWidth = 1;
            field.layer.borderColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1].CGColor;
            field;
        });
    }
    return _passwordField;
}

-(UIButton *)logButton{
    if (!_logButton) {
        _logButton = ({
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.layer.cornerRadius = 5;
            btn.backgroundColor = [UIColor colorWithRed:0/255.0 green:145/255.0 blue:234/255.0 alpha:1];
            [btn setTitle:@"登录" forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(loginForButton:) forControlEvents:UIControlEventTouchDown];
            btn;
        });
    }
    return _logButton;
}

#pragma mark - Tools Methods

+(GKZYLoginUserInfoEntity *)archiveLogEntity{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *entityData = [userDefaults valueForKey:OO_USER_INFO_KEY];
    if (!entityData) {
        return nil;
    }
    GKZYLoginUserInfoEntity *userInfoEntity = [NSKeyedUnarchiver unarchiveObjectWithData:entityData];
    
    return userInfoEntity;
}

-(void)alterError:(NSNotification *)notification{
    [self alterErrorWithMsg:[notification object]];
}

-(void)alterErrorWithMsg:(NSString *)msg{
    JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
    HUD.textLabel.text = msg;
    HUD.indicatorView = [[JGProgressHUDErrorIndicatorView alloc] init];
    [HUD showInView:self.view];
    [HUD dismissAfterDelay:2.0];
}

-(void)alert:(NSString *)massage withComplete:(void(^)())block {
    UILabel *alertLabel = [[UILabel alloc] init];
    alertLabel.frame = CGRectMake(self.view.frame.size.width/3,self.view.frame.size.height-80 , self.view.frame.size.width/3,20);
    alertLabel.backgroundColor = [UIColor darkGrayColor];
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.text = massage;
    alertLabel.layer.cornerRadius = 2.0;
    alertLabel.layer.masksToBounds = YES;
    alertLabel.textColor = [UIColor whiteColor];
    alertLabel.font = [UIFont systemFontOfSize:12.0];
    [alertLabel sizeToFit];
    [self.view addSubview:alertLabel];
    [UIView animateWithDuration:1.2 animations:^{
        alertLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [alertLabel removeFromSuperview];
        if (block) { block(); }
    }];
}

/**
 * 图标转图片
 **/
-(UIImage*)imageWithText:(NSString*)characterCodeString font:(UIFont*)font iconColor:(UIColor*)iconColor imageSize:(CGSize)imageSize{
    NSAssert(characterCodeString, @"必须有内容，比如$");
    if (!iconColor)
    {
        iconColor = [UIColor blackColor];
    }
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    NSAttributedString *attString = [[NSAttributedString alloc] initWithString:characterCodeString attributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:iconColor}];
    
    //生成目标区域 用来居中图片
    NSStringDrawingContext *ctx = [[NSStringDrawingContext alloc] init];
    CGRect boundingRect = [attString boundingRectWithSize:CGSizeMake(font.pointSize, font.pointSize) options:NSStringDrawingUsesLineFragmentOrigin context:ctx];
    
    //往图片里画图标
    [attString drawInRect:CGRectMake((imageSize.width/2.0f) - boundingRect.size.width/2.0f,
                                     (imageSize.height/2.0f) - boundingRect.size.height/2.0f,
                                     imageSize.width,
                                     imageSize.height)];
    UIImage *iconImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return iconImage;
}

/**
 * 全局取消键盘
 **/
-(void)hideKeyBoard{
    for (UIWindow* window in [UIApplication sharedApplication].windows){
        for (UIView* view in window.subviews){
            [self dismissAllKeyBoardInView:view];
        }
    }
}

-(BOOL)dismissAllKeyBoardInView:(UIView *)view{
    if([view isFirstResponder]){
        [view resignFirstResponder];
        return YES;
    }
    
    for(UIView *subView in view.subviews){
        if([self dismissAllKeyBoardInView:subView]){
            return YES;
        }
    }
    return NO;
}

@end
